package com.bw.base.mvvm

import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VDB : ViewDataBinding,VM : BaseViewModel> : Fragment() {
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val binding:VDB by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate",layoutInflater::class.java)
        method.invoke(null,layoutInflater) as VDB
    }
    protected val vm:VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(requireActivity())[clazz]
    }

    fun onError(t:Throwable){
        ToastUtils.showLong(t.message)
        Log.e("TAG", "onError: ${t.message}}", )
        t.printStackTrace()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        vm.onFailed.observe(requireActivity(),::onError)
        initView()
        initData()
    }

    abstract fun initView()

    abstract fun initData()
}